#-*- coding:utf-8 -*-

import urllib.request
import json
import csv
import time
import datetime


def jd_price(sku):
# def jd_price(url):
    # sku = url.split('/')[-1].strip(".html")
    # print "number:" + sku
    price_url = "https://p.3.cn/prices/mgets?skuIds=J_" + sku
    response = urllib.request.urlopen(price_url)
    content = response.read()
    # print(content)
    # print(type(content))
    # print "content:" + content
    result = json.loads(str(content, encoding="utf-8"))
    # print result
    # print result[0]
    record = result[0]
    # print "price:", record['p']
    # print type(record['p'])
    return record['p']


def write_csv(path, data_row):
    with open(path,'a+',encoding='utf-8-sig') as csvfd:
        csv_writer = csv.writer(csvfd)
        csv_writer.writerow(data_row)


if __name__=="__main__":
    # jd_price("https://item.jd.com/55305481221.html")

    product = []

    # info_dict = {'name':"技嘉（GIGABYTE）B365M AORUS ELITE 主板+英特尔 i5-9400F板U套装/主板+CPU套装", 'number':'100005718612'}
    # product.append(info_dict)
    # info_dict = {'name':"微星（MSI）B450M MORTAR MAX迫击炮 电竞主板+ AMD 锐龙 5 3600X处理器 (r5) 盒装CPU 主板CPU套装", 'number':'100007470464'}
    # product.append(info_dict)

    info_dict = {'number':'3180109', 'name':"金士顿(Kingston) DDR4 2666 8GB 台式机内存条 骇客神条 Fury雷电系列"}
    product.append(info_dict)

    # print product

    while True:
        while True:
            time.sleep(1)

            now = datetime.datetime.now()
            # if now.hour == h and now.minute == m and now.second == s:
            if now.second % 5 == 0:
                break

        print(now)

        for i in product:
            # print "check %s number %s" % (i['name'], i['number'])
            # print "%s: %s" % (i['name'], jd_price(i['number'])) 
            # print jd_price(i['number']), i['name']

            path = i['number'] + ".csv"
            print(path)
            data_row = [now, jd_price(i['number']), i['name']]
            write_csv(path, data_row)
